Mongoose
About
-
Mongoose .
-
It's a wrapper for MongoDB.
-
Is Mongoose an ORM?
-
Mongoose is not technically an ORM (Object-Relational Mapping), but rather an ODM (Object-Document Mapping).
-
Although both ORM and ODM have similar goals — mapping objects in code to database entities — the difference is the type of database each one handles.
-
Explanations
-
HTTP Server with CRUD API and Mongoose database .
-
The presenter uses Mongoose Atlas, but it should not make a difference.
-
The video is of poor quality and poorly explained, but if you have some background before watching it, it is possible to watch it without quitting.
-
{33:47}:
-
Schema and Model created.
-
Connection established with the Mongoose server.
-
-
{49:10}:
-
Create a GET that receives an ID in the URL as a parameter.
-
-
{58:37}:
-
Update a product based on the ID, with PUT.
-
-
Database
-
-
I don't really know yet where the DB lives on the filesystem.
-
There are files inside
Program Files/mongodb.
-
-
Schemas and Models
-
Creating a Schema and Model:
import mongoose from 'npm:mongoose';
mongoose.connect('mongodb://localhost/meu_banco', { useNewUrlParser: true, useUnifiedTopology: true });
const user_schema = new mongoose.Schema({
nome: { type: String, required: true },
email: { type: String, required: true, unique: true },
idade: { type: Number, min: 18 }
});
const User = mongoose.model('User', user_schema);
-
Collection name:
-
.
-
Documents
-
Via
new Modeland.save
const new_user = new User({
nome: 'John',
email: 'john@email.com',
idade: 25
});
new_user.save()
.then(() => console.log('User saved!'))
.catch((err) => console.log('Error saving the user:', err));
-
Via
.create:
const new_character = await Character.create({
nome: 'John',
});
Validations
-
Taken from the video above .
-
A schema created by default has its properties set as 'not required'.
-
.
-
.
-
.
-
.